package server;


import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class Host {
    private String appBase;
    private Map<String, Context> contextMap;

    public Host(String appBase) {
        this.appBase = appBase;
        contextMap = new HashMap<>();
    }

    public void init() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
        File appBasePath = new File(appBase);

        File[] files = appBasePath.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                String contextName = file.getName();
                Context context = new Context(appBase,contextName);
                context.init();
                contextMap.put(contextName, context);
            }
        }
    }

    public void start() {
        for (Map.Entry<String, Context> entry : contextMap.entrySet()) {
            entry.getValue().start();
        }
    }

    public void process(Request request, Response response, MappedData mappedData) throws Exception {
        Context context = contextMap.get(mappedData.getMappedContext());
        if (context == null) {
            throw new MappingException();
        }

        context.process(request, response, mappedData);
    }
}
